#!/bin/bash

# celery worker的控制脚本

CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
THIS_SCRIPT="${CURRENT_DIR}/$(basename $0)"
PROJECT_FOLDER="$(dirname $(dirname ${CURRENT_DIR}))"

# 解决python的ssl依赖问题
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${PROJECT_FOLDER}/component/env/lib/

APP_NAME="worker"

start() {
  real_status
  if [ $? -eq 0 ];then
    echo "${APP_NAME} [running]"
    return 0
  else
    cd $PROJECT_FOLDER/omp_server
    nohup $PROJECT_FOLDER/component/env/bin/python3 $PROJECT_FOLDER/component/env/bin/celery \
    -A omp_server worker --loglevel=ERROR >$PROJECT_FOLDER/logs/celery_worker.log  2>&1 &
    echo "${APP_NAME} [running]"
  fi
}

stop() {
  real_status
  if [ $? -eq 1 ]; then
    echo "${APP_NAME} [not running]"
    return 0
  else
    ps -ef | grep "${PROJECT_FOLDER}/component/env/bin/celery" |grep -v scheduler | grep -v grep | cut -c 9-15 | xargs kill -9
    sleep 3
    real_status
    if [ $? -eq 0 ]; then
      echo "${APP_NAME} [running]"
      return 1
    else
      echo "${APP_NAME} [not running]"
      return 0
    fi
  fi
}

real_status() {
  worker_status=$(ps -ef | grep ${PROJECT_FOLDER}/component/env/bin/celery | grep -v scheduler | grep -v grep)
  if [ -n "$worker_status" ]; then
    return 0
  else
    return 1
  fi
}

status() {
  real_status
  if [ $? -eq 0 ]; then
    echo "${APP_NAME} [running]"
    return 0
  else
    echo "${APP_NAME} [not running]"
    return 1
  fi
}

case $1 in
start) start ;;
stop) stop ;;
restart)
  stop
  start
  ;;
status)
  status
  ;;
*)
  echo "usage: $0 [start|stop|restart|status]"
  ;;
esac
